package com.guyaogg.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guyaogg.common.utils.PageUtils;
import com.guyaogg.common.utils.Query;
import com.guyaogg.common.utils.R;
import com.guyaogg.common.utils.StringUtils;
import com.guyaogg.gulimall.ware.dao.WareInfoDao;
import com.guyaogg.gulimall.ware.entity.WareInfoEntity;
import com.guyaogg.gulimall.ware.feign.MemberFeignService;
import com.guyaogg.gulimall.ware.service.WareInfoService;
import com.guyaogg.gulimall.ware.vo.FareVO;
import com.guyaogg.gulimall.ware.vo.MemberAddressVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.Map;


@Service("wareInfoService")
public class WareInfoServiceImpl extends ServiceImpl<WareInfoDao, WareInfoEntity> implements WareInfoService {

    @Autowired
    private MemberFeignService memberFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareInfoEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            String trimKey = key.trim();
            wrapper.eq("id", trimKey)
                    .or().like("name", trimKey)
                    .or().like("address", trimKey)
                    .or().like("areacode", trimKey);
        }
        IPage<WareInfoEntity> page = this.page(
                new Query<WareInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public FareVO getFare(Long addrId) {
        R r = memberFeignService.addrInfo(addrId);
        MemberAddressVO data = r.getData("memberReceiveAddress", new TypeReference<MemberAddressVO>() {
        });
        FareVO fareVO = new FareVO();

        if (data != null) {
            fareVO.setAddress(data);
            // TODO 运费计算
            String phone = data.getPhone();
            if (!ObjectUtils.isEmpty(phone)) {
                String substring = phone.substring(phone.length() - 1);
                fareVO.setFare( new BigDecimal(substring));
                return fareVO;
            }
        }
        return fareVO;
    }

}